﻿using Engine;
using Game;
using GameEntitySystem;
using TemplatesDatabase;

namespace SAGhoul
{
	public class SubsystemMultipleThrowableBlockBehavior : SubsystemBlockBehavior  //多重射击
	{
		public SubsystemAudio m_subsystemAudio;           // 音频子系统
		public SubsystemProjectiles m_subsystemProjectiles; // 投射物子系统
		public Game.Random m_random = new();   // 随机数生成器

		// 定义该子系统处理的方块ID
		public override int[] HandledBlocks => new int[0];

		// 瞄准/投掷行为处理
		public override bool OnAim(Ray3 aim, ComponentMiner componentMiner, AimState state)
		{
			switch (state)
			{
				case AimState.InProgress: // 瞄准状态
				{
					// 设置手部瞄准角度
					componentMiner.ComponentCreature.ComponentCreatureModel.AimHandAngleOrder = 1.0f;

					Block block2 = BlocksManager.Blocks[Terrain.ExtractContents(componentMiner.ActiveBlockValue)];
					ComponentFirstPersonModel componentFirstPersonModel = componentMiner.Entity.FindComponent<ComponentFirstPersonModel>();

					if (componentFirstPersonModel != null)
					{
						// 显示准星
						componentMiner.ComponentPlayer?.ComponentAimingSights.ShowAimingSights(aim.Position, aim.Direction);
						componentFirstPersonModel.ItemOffsetOrder = new Vector3(0f, 0.35f, 0.17f);

					}
					break;
				}

				case AimState.Completed: // 完成投掷状态
				{
					// 计算发射位置和方向
					Vector3 position = componentMiner.ComponentCreature.ComponentCreatureModel.EyePosition +
									 (componentMiner.ComponentCreature.ComponentBody.Matrix.Right * 0.2f);
					var direction = Vector3.Normalize(position + (aim.Direction * 10f) - position);

					if (componentMiner.Inventory == null)
						break;

					int activeSlotIndex = componentMiner.Inventory.ActiveSlotIndex;
					int slotValue = componentMiner.Inventory.GetSlotValue(activeSlotIndex);
					int slotCount = componentMiner.Inventory.GetSlotCount(activeSlotIndex);
					int blockId = Terrain.ExtractContents(slotValue);
					Block block = BlocksManager.Blocks[blockId];

					if (slotCount > 0)
					{
						// 计算基础投射速度
						float projectileSpeed = block.GetProjectileSpeed(slotValue);

						// 应用玩家力量加成
						if (componentMiner.ComponentPlayer != null)
						{
							projectileSpeed *= (0.5f * ((componentMiner?.ComponentFactors?.StrengthFactor ?? 1f) - 1f)) + 1f;
						}

						Vector3 baseVelocity = componentMiner.ComponentCreature.ComponentBody.Velocity + direction * projectileSpeed;
						bool allProjectilesCreated = true;
						Projectile[] projectiles = new Projectile[8];

						// 创建5个从同一位置发射但速度递减的投射物
						for (int i = 0; i < 8; i++)
						{
							// 增大速度递减幅度（从原来的5%增加到15%）
							float speedFactor = 1f - i * 0.13f; // 每个投射物速度递减15%
							Vector3 velocity = baseVelocity * speedFactor;

							// 添加随机扰动
							velocity += m_random.Vector3(0f, 0.2f);

							projectiles[i] = m_subsystemProjectiles.FireProjectile(
								slotValue,
								position,
								velocity,
								m_random.Vector3(5f, 10f),
								componentMiner.ComponentCreature);

							if (projectiles[i] == null)
							{
								allProjectilesCreated = false;
								break;
							}
						}

						if (allProjectilesCreated)
						{
							// 消耗物品并播放音效
							componentMiner.Inventory.RemoveSlotItems(activeSlotIndex, 1);
							m_subsystemAudio.PlaySound("Audio/Throw", m_random.Float(0.2f, 0.3f),
								m_random.Float(-0.2f, 0.2f), aim.Position, 2f, autoDelay: true);
							componentMiner.Poke(forceRestart: false);
						}
					}
					break;
				}
			}
			return false;
		}
		public override bool OnHitAsProjectile(CellFace? cellFace, ComponentBody componentBody, WorldItem worldItem)
		{
			if (componentBody?.Entity?.FindComponent<ComponentSAGhouls>() != null && worldItem is Projectile projectile)
			{
				projectile.AttackPower *= 20f;
			}
			return base.OnHitAsProjectile(cellFace, componentBody, worldItem);
		}

		// 初始化子系统
		public override void Load(ValuesDictionary valuesDictionary)
		{
			m_subsystemAudio = Project.FindSubsystem<SubsystemAudio>(throwOnError: true);
			m_subsystemProjectiles = Project.FindSubsystem<SubsystemProjectiles>(throwOnError: true);
			base.Load(valuesDictionary);
		}
	}
}